package com.zhenyi.liuxue.mini;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.liuxue.common.model.LxMajor;
import com.liuxue.common.model.LxPolicy;
import com.liuxue.common.model.LxQuestion;
import com.liuxue.common.model.LxSchool;
import com.liuxue.common.model.LxSchoolMajor;
import com.liuxue.common.model.LxStatistic;
import com.liuxue.common.model.LxSubscribe;
import com.liuxue.common.model.LxUkSchool;
import com.liuxue.common.model.LxUser;
import com.zhenyi.liuxue.interceptor.SchoolVisitiInterceptor;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class SchoolController extends MiniController {

	/**
	 * 学校列表
	 */
	// @Before(CacheInterceptor.class)
	// @CacheName("hour1")
	@Override
	public void list() {
		// SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindSchools");
		// Page<LxSchool> pages = LxSchool.dao.paginate(getPage(), PAGE_SIZE,
		// sqlPara);
		LxUser user = getUser();
		String from = "FROM lx_school";
		if (user != null) {
			from += " LEFT JOIN lx_subscribe ON lx_subscribe.schoolId = lx_school.id AND lx_subscribe.userId = "
					+ user.getId();
		}
		String totalRowSql = "SELECT count(*) " + from;
		String findSql = null;
		// String orderBy = " ORDER BY convert(lx_school.`name` using gbk) ASC";
		String orderBy = " ORDER BY lx_school.sort ASC";
		if (user != null) {
			findSql = "SELECT lx_school.*, lx_subscribe.userId " + from + orderBy;
		} else {
			findSql = "SELECT lx_school.* " + from + orderBy;
		}
		Page<LxSchool> pages = LxSchool.dao.paginateByFullSql(getPage(), PAGE_SIZE, totalRowSql, findSql);
		renderResult(pages);
	}

	// @Before({ SchoolVisitiInterceptor.class, CacheInterceptor.class })
	// @CacheName("hour1")
	@Before(SchoolVisitiInterceptor.class)
	@Override
	public void info() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxSchool info = LxSchool.dao.findById(id);
		if (info == null) {
			renderFailure(404, "school not found");
			return;
		}
		if (StrKit.notBlank(info.getRates())) {
			// String[] rates = info.getRates().split(";");
			// info.set("rates", rates);
			info.set("rates", JSONUtil.parseArray(info.getRates()));
		}
		if (StrKit.notBlank(info.getAdvantageMajors())) {
			String[] majorIds = info.getAdvantageMajors().split(";");
			ArrayList<LxMajor> majorList = new ArrayList<>();
			for (String majorId : majorIds) {
				LxMajor major = LxMajor.dao.findById(majorId);
				majorList.add(major);
			}
			info.put("majorList", majorList);
		}
		// Kv kv = Kv.create();
		// kv.set("schoolId", info.getId());
		// SqlPara sqlPara =
		// Db.use("liuxue").getSqlPara("LXFindSchoolRequirements", kv);
		// List<Record> requirements = Db.use("liuxue").find(sqlPara);
		if (StrKit.notBlank(info.getRequirement())) {
			JSONArray requirements = JSONUtil.parseArray(info.getRequirement());
			info.put("requirements", requirements);
		}

		LxUser user = getUser();
		if (user != null) {
			LxSubscribe subscribe = LxSubscribe.dao.findById(info.getId(), user.getId());
			if (subscribe != null) {
				info.put("subscribed", 1);
			} else {
				info.put("subscribed", 0);
			}
		}

		// 统计
		LxStatistic stat = new LxStatistic();
		stat.setSchoolId(id);
		stat.setType(1);
		stat.save();

		renderResult(info);
	}

	@Before({ SchoolVisitiInterceptor.class, CacheInterceptor.class })
	@CacheName("hour1")
	public void major() {
		Long schoolId = getParaToLong("schoolId");
		String keyword = getPara("keyword");
		String filter = getPara("filter");

		Kv kv = Kv.create();
		if (schoolId != null) {
			kv.set("schoolId", schoolId);
		}
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
		}
		if (StrKit.notBlank(filter)) {
			JSONObject filterObj = JSONUtil.parseObj(filter);
			if (!filterObj.isNull("rank") && StrKit.notBlank(filterObj.getStr("rank"))) {
				kv.set("rank", filterObj.getStr("rank"));
			}
			if (!filterObj.isNull("department") && StrKit.notBlank(filterObj.getStr("department"))) {
				kv.set("department", filterObj.getStr("department"));
			}
			if (!filterObj.isNull("category") && StrKit.notBlank(filterObj.getStr("category"))) {
				kv.set("category", filterObj.getStr("category"));
			}
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindMajors", kv);
		Page<LxMajor> pages = LxMajor.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderResult(pages);
	}

	@Before(CacheInterceptor.class)
	@CacheName("hour1")
	public void majorInfo() {
		// lx_major.id
		Long majorId = getParaToLong("majorId");

		// lx_school_major.id 录取标准模块提交的数据
		Long schoolMajorId = getParaToLong("schoolMajorId");
		Long schoolId = getParaToLong("schoolId");
		Long majorRankScoreId = getParaToLong("majorRankScoreId");

		if (majorId != null) {
			LxMajor info = LxMajor.dao.findById(majorId);
			if (info == null) {
				renderFailure(404, "major not found");
				return;
			}
			info.setVisitCount(info.getVisitCount() + 1);
			info.update();
			LxSchool school = LxSchool.dao.findById(info.getSchoolId());
			info.put("schoolName", school.getName());
			renderResult(info);

			// 统计
			LxStatistic stat = new LxStatistic();
			stat.setSchoolId(school.getId());
			stat.setMajorId(majorId);
			stat.setType(2);
			stat.save();

		} else if (schoolMajorId != null && schoolId != null) {
			LxUkSchool ukSchool = LxUkSchool.dao.findById(schoolId);
			LxSchoolMajor schoolMajor = LxSchoolMajor.dao.findById(schoolMajorId);

			Kv kv = Kv.create();
			kv.set("majorEngName", schoolMajor.getName());
			kv.set("schoolName", ukSchool.getName());
			kv.set("majorRankScoreId", majorRankScoreId);
			SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindMajorsByNameAndSchool", kv);
			LxMajor major = LxMajor.dao.findFirst(sqlPara);
			if (major == null) {
				renderFailure(404, "暂未找到该专业介绍");
				return;
			}
			major.setVisitCount(major.getVisitCount() + 1);
			major.update();
			renderResult(major);

			// 统计
			LxStatistic stat = new LxStatistic();
			stat.setSchoolId(schoolId);
			stat.setMajorId(major.getId());
			stat.setType(2);
			stat.save();

		} else {
			renderFailure(500, "param error");
			return;
		}
	}

	public void departments() {
		Long schoolId = getParaToLong("schoolId");
		if (schoolId == null) {
			renderFailure(500, "school id required");
			return;
		}
		Kv kv = Kv.create();
		kv.set("schoolId", schoolId);
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindSchoolDepartments", kv);
		List<Record> list = Db.use("liuxue").find(sqlPara);
		String[] result = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			result[i] = list.get(i).getStr("department");
		}
		renderResult(result);
	}

	public void categories() {
		Long schoolId = getParaToLong("schoolId");
		Integer rank = getParaToInt("rank");
		String department = getPara("department");
		if (schoolId == null) {
			renderFailure(500, "school id required");
			return;
		}
		if (StrKit.isBlank(department)) {
			renderFailure(500, "department is required");
			return;
		}
		Kv kv = Kv.create();
		kv.set("schoolId", schoolId);
		kv.set("department", department);
		if (rank != null) {
			kv.set("rank", rank);
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindSchoolCategories", kv);
		List<Record> list = Db.use("liuxue").find(sqlPara);
		ArrayList<String> result = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			if (StrKit.notBlank(list.get(i).getStr("category"))) {
				result.add(list.get(i).getStr("category"));
			}
		}
		renderResult(result);
	}

	/**
	 * 申请政策
	 */
	// @Before({ SchoolVisitiInterceptor.class, CacheInterceptor.class })
	// @CacheName("hour1")
	public void policy() {
		Long schoolId = getParaToLong("schoolId");
		String keyword = getPara("keyword");
		Kv kv = Kv.create();
		if (schoolId != null) {
			kv.set("schoolId", schoolId);
		}
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindPolicies", kv);
		// List<Record> list = Db.use("liuxue").find(sqlPara);
		Page<Record> pages = Db.use("liuxue").paginate(getPage(), PAGE_SIZE, sqlPara);
		// ArrayList<Record> arrayList = new ArrayList<>();
		List<Record> list = pages.getList();
		for (Record record : list) {
			Long policyId = record.getLong("id");
			if (!isPolicyInRange(policyId)) {
				list.remove(record);
			}
			// if (isPolicyInRange(policyId)) {
			// arrayList.add(record);
			// }
		}
		renderSuccess(pages);
	}

	/**
	 * 申请政策详情
	 */
	// @Before(CacheInterceptor.class)
	// @CacheName("hour1")
	public void policyInfo() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxPolicy info = LxPolicy.dao.findById(id);
		if (info == null) {
			renderFailure(404, "not found");
			return;
		}
		if (!isPolicyInRange(info.getId())) {
			renderFailure(404, "not found");
			return;
		}
		renderSuccess(info);

		// 统计
		LxStatistic stat = new LxStatistic();
		stat.setSchoolId(info.getSchoolId());
		stat.setPolicyId(id);
		stat.setType(3);
		stat.save();
	}

	public void countDownload() {
		Long policyId = getParaToLong("policyId");
		if (policyId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxPolicy policy = LxPolicy.dao.findById(policyId);
		LxStatistic stat = new LxStatistic();
		stat.setSchoolId(policy.getSchoolId());
		stat.setPolicyId(policyId);
		stat.setType(6);
		stat.save();
		renderSuccess();
	}

	/**
	 * 常见问题
	 */
	@Before(CacheInterceptor.class)
	@CacheName("hour1")
	public void question() {
		Long schoolId = getParaToLong("schoolId");
		String keyword = getPara("keyword");
		if (schoolId == null) {
			renderFailure(500, "school id is null");
			return;
		}
		Kv kv = Kv.create();
		kv.set("schoolId", schoolId);
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindQuestions", kv);
		List<Record> list = Db.use("liuxue").find(sqlPara);
		renderSuccess(list);

		// 统计
		LxStatistic stat = new LxStatistic();
		stat.setSchoolId(schoolId);
		stat.setType(4);
		stat.save();
	}

	public void visitQuestion() {
	}

	public void clickQuestion() {
		Long questionId = getParaToLong("questionId");
		if (questionId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxQuestion info = LxQuestion.dao.findById(questionId);
		if (info == null) {
			renderFailure(404, "not found");
			return;
		}
		info.setVisit(info.getVisit() + 1);
		info.update();
		renderSuccess();
	}

	public void subscribe() {
		Long schoolId = getParaToLong("schoolId");
		LxUser user = getUser();
		if (schoolId == null) {
			renderFailure(500, "school id is required");
			return;
		}
		if (user == null) {
			renderFailure(500, "请先登录");
			return;
		}
		LxSubscribe subscribe = LxSubscribe.dao.findById(schoolId, user.getId());
		if (subscribe != null) {
			renderFailure(500, "您已经订阅了");
			return;
		}
		subscribe = new LxSubscribe();
		subscribe.setSchoolId(schoolId);
		subscribe.setUserId(user.getId());
		subscribe.setAddTime();
		renderFlag(subscribe.save());
	}

	public void unsubscribe() {
		Long schoolId = getParaToLong("schoolId");
		LxUser user = getUser();
		if (schoolId == null) {
			renderFailure(500, "school id is required");
			return;
		}
		if (user == null) {
			renderFailure(500, "请先登录");
			return;
		}
		LxSubscribe subscribe = LxSubscribe.dao.findById(schoolId, user.getId());
		if (subscribe == null) {
			renderFailure(500, "未订阅");
			return;
		}
		renderFlag(subscribe.delete());
	}
}
